package cn.com.victorysoft.ylgl.service.commons.mybatis;

import cn.com.victorysoft.ylgl.service.commons.mybatis.paging.PaginationInterceptor;
import cn.com.victorysoft.ylgl.service.commons.mybatis.paging.bean.DataPaging;
import cn.com.victorysoft.ylgl.service.commons.mybatis.paging.bean.Pageable;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/***
 * @author gechaoqing
 */
@Component
public class SqlSessionDao
{
    private SqlSession sqlSession;

    @Resource
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate)
    {
        this.sqlSession = sqlSessionTemplate;
    }

    public SqlSession getSqlSession()
    {
        return this.sqlSession;
    }

    public <T> T selectById(String statement, String id)
    {
        return this.sqlSession.selectOne(statement, id);
    }

    public <T> T selectOne(String statement, Object key)
    {
        return this.sqlSession.selectOne(statement, key);
    }

    public <E> List<E> selectByParams(String statement, Object params)
    {
        return this.sqlSession.selectList(statement, params);
    }

    public <E> DataPaging<E> selectPaging(String statement, Pageable pageable)
    {
        RowBounds rowBounds = new RowBounds(pageable.getOffset(), pageable.getLimit());
        List<E> rows = this.sqlSession.selectList(statement, pageable.getParameters(), rowBounds);

        int total = rows.size();
        if (pageable.getLimit() != Integer.MAX_VALUE)
        {
            total = PaginationInterceptor.getPaginationTotal();
            PaginationInterceptor.clean();
        }
        return new DataPaging<>(rows, total);
    }

    public void insert(String statement, Object params)
    {
        this.sqlSession.insert(statement, params);
    }

    public void update(String statement, Object params)
    {
        this.sqlSession.update(statement, params);
    }

    public void delete(String statement, Object params)
    {
        this.sqlSession.delete(statement, params);
    }
}
